package com.su.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.su.common.R;
import com.su.dto.DishDto;
import com.su.pojo.Category;
import com.su.pojo.Dish;
import com.su.pojo.DishFlavor;
import com.su.service.CategoryService;
import com.su.service.DishFlavorService;
import com.su.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveDishAndDishFlavor(dishDto);
        //清除redis缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("菜品添加成功");
    }

    /**
     * 分页展示菜品信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> getByPage(int page, int pageSize, String name) {
        //菜品基本信息
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //查询菜品信息
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, lqw);

        //获取菜品分类的名称
        //1.获取所有分类的id存到set集合中（去重）
        List<Dish> records = dishPage.getRecords();
        Set<Long> categoryIdStet = records.stream().map(record -> record.getCategoryId()).collect(Collectors.toSet());
        //2.查询所有category
        List<Category> categoryList = categoryService.listByIds(categoryIdStet);
        //3.获取id和name的键值对集合
        Map<Long, String> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        //4.赋值
        for (Dish record : records) {
            Long categoryId = record.getCategoryId();
            String categoryName = categoryMap.get(categoryId);
            record.setCategoryName(categoryName);
        }
        return R.success(dishPage);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getByIdWithFlavor(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateByIdWithFlavor(@RequestBody DishDto dishDto) {
        dishService.updateByIdWithFlavor(dishDto);
        //清除redis缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 停售，批量停售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatue(@PathVariable int status, @RequestParam List<Long> ids) {
        //log.info("status {},ids {}", status, ids);
        dishService.updateStatue(status, ids);
        //清除redis缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    /**
     * 删除菜品-- 批量删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam List<Long> ids) {
        dishService.removeByIds(ids);
        //清除redis缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }

    /**
     * 获取菜品分类列表
     *
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> getList(Dish dish) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        dishLambdaQueryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
        dishLambdaQueryWrapper.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        return R.success(list);
    }*/

    /**
     * 展示菜品信息同时展示口味信息
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getList(Dish dish) {
        List<DishDto> dishDtoList = null;
        //动态构造Key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据id查询
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //启用的才参与查询，查询状态是1的
        lqw.eq(Dish::getStatus, 1);
        //菜品名称模糊查询
        lqw.like(dish.getName() != null, Dish::getName, dish.getName());
        //根据修改时间降序排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        //通过dish_id查询所有菜品需要的口味信息
        Set<Long> dishIds = list.stream().map(dish1 -> dish1.getId()).collect(Collectors.toSet());
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DishFlavor::getDishId, dishIds);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);       //此时集合里面放的都是口味的信息

        //循环遍历将菜品的基本信息和口味信息封装到DishDto中,然后放到list集合中返回
        dishDtoList = new ArrayList<>();
        for (Dish dish2 : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish2, dishDto);
            List<DishFlavor> collect = dishFlavorList.stream().filter(dishFlavor -> dishFlavor.getDishId().equals(dishDto.getId())).collect(Collectors.toList());
            dishDto.setFlavors(collect);
            dishDtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}